package com.agileai.portal.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.broker.BrokerService;
import org.apache.log4j.Logger;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.common.Constants.FrameHandlers;
import com.agileai.hotweb.common.HandlerParser;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.hotweb.servlet.DispatchServlet;

public class PortletAppDispatchServlet extends DispatchServlet {
	private static final long serialVersionUID = 1L;
	private static BrokerService broker;
	public static ServletContext servletContext = null; 
	protected Logger LOG = Logger.getLogger(PortletAppDispatchServlet.class);

	protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		log.debug("DispatchServlet------start");
		try {
			ViewRenderer viewRenderer = null;
			String handlerId = parseHandlerId(request);
			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			List<String> publicHandlerIdList = PublicHandlerIdListCache.get(classLoader);
			if (isExpired(request) && !FrameHandlers.LoginHandlerId.equals(handlerId)
					&& !publicHandlerIdList.contains(handlerId)){
				viewRenderer = new RedirectRenderer(request.getContextPath());
			} else {
				BaseHandler handler = HandlerParser.getOnly().instantiateHandler(handlerId);
				handler.setDispatchServlet(this);
				handler.setRequest(request);
				handler.setResponse(response);
				DataParam param = new DataParam(request.getParameterMap());
				viewRenderer = handler.processRequest(param);
				viewRenderer.setHandler(handler);
			}
			viewRenderer.executeRender(this, request, response);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.debug("DispatchServlet------end");
	}

	@Override
	protected void initResource() {
		super.initResource();
		servletContext = getServletContext();
		this.initEmbedActiveMq();
				
	}
	protected void initEmbedActiveMq() {
		String mqconn = getInitParameter("mqconn");
		String mqStart = getInitParameter("mqstart");
		log.info("initEmbedActiveMq ....");
		if (Boolean.parseBoolean(mqStart)) {
	        try {
		        broker = new BrokerService();
		        broker.setUseJmx(false);
				broker.addConnector(mqconn);
		        broker.setDataDirectory(getDataPath());
		    	broker.start();
		    	log.info("initEmbedActiveMq successfully !");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}	
	
	public static String getDataPath(){
		String result = null;
		String realPath = servletContext.getRealPath("/");
		String tempPath = realPath.replaceAll("\\\\", "/");
		if (tempPath.endsWith("/")){
			tempPath = tempPath.substring(0,tempPath.length()-1);
		}
		tempPath = tempPath.substring(0,tempPath.lastIndexOf("/"));
		result = tempPath.substring(0,tempPath.lastIndexOf("/"))+ "/data";
		File dataDir = new File(result);
		if (!dataDir.exists()){
			dataDir.mkdirs();
		}
		return result;
	}		
	
}